<?php
namespace app\index\controller;

use app\common\model\Fruit as FruitModel;

use app\common\component\fruit\FruitService;
use app\common\component\fruit\FruiteSellService;

class FruitSell extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

    public function index() {
    	$userId = \think\Session::get('user_id');

		$fruitServiceFind = (new FruitService()) -> find($userId);
		if(isset($fruitServiceFind['data']['fruit']['fruit_second_profit'])) {
			$this -> view -> assign('fruitSecondProfit', $fruitServiceFind['data']['fruit']['fruit_second_profit']);
		} else {
			$this -> view -> assign('fruitSecondProfit', 0);
		}

        return $this -> view -> fetch();
    }
	
	public function handleSell() {
		$post = $this -> request -> post();

		if($this -> validate($post, ['price' => 'require|token']) !== true) {
			echo '<script>window.location.href="/fruit/sell";</script>';exit;
		}

		if(!in_array($post['fruit'], ['second'])) {
			echo '<meta charset="utf-8"><script>alert("请选择正确的果子!");window.history.go(-1);</script>';exit;
		}

		$userId = \think\Session::get('user_id');

		$fruitServiceFind = (new FruitService()) -> find($userId);
		switch($post['fruit']) {
			case 'second':
				$fruitClass = 'FruitSecond';
				$fruitKey = 'fruit_second_profit';
				$fruiteSellType = 2;
				break;
		}

		if($post['price'] > $fruitServiceFind['data']['fruit'][$fruitKey]) {
			echo '<meta charset="utf-8"><script>alert("你兑换的额度大于您拥有的果子!");window.history.go(-1);</script>';exit;
		}

		$resultCheckPayPassword = (new \app\common\component\user\UserService()) -> checkPayPassword($post['pay_password']);
    	if($resultCheckPayPassword['code'] !== 0) {
    		echo '<meta charset="utf-8"><script>alert("' . $resultCheckPayPassword['message'] . '!");window.history.go(-1);</script>';exit;
    	}

		$currentTime = time();
		\think\Db::startTrans();
		try {
			if(!FruitModel::where('user_id', $userId) -> setDec($fruitKey, $post['price'])) {
				throw new \Exception('兑换额度失败, FruitModel setDec!');
			}

			$classLog = '\\app\\common\\component\\fruit\\' . $fruitClass . 'LogService';
			$fruitLogServiceCreate = (new $classLog()) -> create([
				'user_id' => $userId,
				'type' => 3,
				'active' => 0,
				'price' => $post['price'],
				'create_time' => $currentTime,
				'remark' => '出售果子'
			]);
			if($fruitLogServiceCreate['code'] != 0) {
				throw new \Exception($fruitLogServiceCreate['message']);
			}

			$fruiteSellServiceCreate = (new FruiteSellService()) -> create([
				'user_id' => $userId,
				'status' => 1,
				'type' => $fruiteSellType,
				'num' => $post['price'],
				'price' => $post['price'],
				'create_time' => $currentTime
			]);
			if($fruiteSellServiceCreate['code'] != 0) {
				throw new \Exception($fruiteSellServiceCreate['message']);
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '");window.history.go(-1);</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("出售成功!");window.location.href="/fruit/sell";</script>';exit;
	}
}
?>